package com.book.lizhi.ui;

import java.io.File;
import java.util.List;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.widget.RemoteViews;
import android.widget.Toast;
import cn.waps.AdInfo;
import cn.waps.AppConnect;

import com.book.lizhi.AppApplication;
import com.book.lizhi.BaseActivity;
import com.book.lizhi.DownloadIntentService;
import com.book.lizhi.R;
import com.book.lizhi.ui.fragment.BaseFragment;
import com.book.lizhi.ui.fragment.BookshelfFragment;
import com.book.lizhi.ui.fragment.NavigationDrawerFragment;
import com.book.lizhi.util.AppLog;
import com.book.lizhi.util.FileUtil;

public class NavActivity extends BaseActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, Callback {
	private static final int HAS_ADV_INFO = 0x124;
	private Handler mHandler;

	/**
	 * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
	 */
	private NavigationDrawerFragment mNavigationDrawerFragment;

	/**
	 * Used to store the last screen title. For use in {@link #restoreActionBar()}.
	 */
	private CharSequence mTitle;

	private String[] CATEGORY = { "图书", "文章", "歌曲", "电影", "加油站" };
	private String[] CATEGORY2 = { "文章", "歌曲", "电影", "加油站" };

	private int backCounter;

	private BroadcastReceiver mDownloadAdReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String id = intent.getStringExtra(DownloadIntentService.EXTRA_PARAM);
			AppConnect.getInstance(getApplicationContext()).downloadAd(NavActivity.this, id);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_nav);

		Toolbar toolbar = (Toolbar) findViewById(R.id.toobar);
		setSupportActionBar(toolbar);

		mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
		mTitle = "励志";

		// Set up the drawer.
		mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
		FragmentManager fragmentManager = getSupportFragmentManager();
		onSectionAttached(0);
		fragmentManager.beginTransaction().replace(R.id.container, BaseFragment.newInstance(0)).commit();

		mHandler = new Handler(this);
		if(!AppApplication.instance.isCheck){
			mHandler.sendEmptyMessageDelayed(HAS_ADV_INFO, 1 * 6* 1000);
		}
		
		LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(mDownloadAdReceiver, new IntentFilter(DownloadIntentService.DOWNLOAD_AD_ACTION));

	}

	@Override
	public void onNavigationDrawerItemSelected(int position) {
		// update the main content by replacing fragments

		FragmentManager fragmentManager = getSupportFragmentManager();
		onSectionAttached(position);
		fragmentManager.beginTransaction().replace(R.id.container, BaseFragment.newInstance(position)).commit();

	}

	public void onSectionAttached(int number) {
		if (AppApplication.instance.isCheck) {
			mTitle = CATEGORY2[number];
		} else {
			mTitle = CATEGORY[number];
		}
	}

	public void restoreActionBar() {
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(mTitle);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (!mNavigationDrawerFragment.isDrawerOpen()) {
			// Only show items in the action bar relevant to this screen
			// if the drawer is not showing. Otherwise, let the drawer
			// decide what to show in the action bar.
			// getMenuInflater().inflate(R.menu.nav, menu);
			menu.clear();
			restoreActionBar();
			return true;
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		AppLog.e("into---[onKeyDown]");
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			BookshelfFragment fragment = (BookshelfFragment) getSupportFragmentManager().findFragmentByTag("图书");
			if (fragment != null) {
				if (fragment.onKeyDown(keyCode, event)) {
					return true;
				}
			}

			if (mNavigationDrawerFragment.isDrawerOpen()) {
				mNavigationDrawerFragment.closeDrawer();
				return true;
			}

			new Thread(new Runnable() {
				public void run() {
					try {
						Thread.sleep(1000);
						backCounter = 0;
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}).start();

			if (backCounter >= 1) {
				finish();
			} else {
				backCounter++;
				Toast.makeText(getApplicationContext(), "再按一次就退出了!", Toast.LENGTH_SHORT).show();
				return true;
			}
			return super.onKeyDown(keyCode, event);
		}
		// else if (keyCode == KeyEvent.KEYCODE_MENU) {
		// showMenu(R.id.action_more);
		// return true;
		// }
		AppLog.e("out---[onKeyDown]");
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean handleMessage(Message msg) {
		if (msg.what == HAS_ADV_INFO) {
			List<?> adInfos = AppConnect.getInstance(getApplicationContext()).getAdInfoList();
			if (adInfos == null || adInfos.size() < 1) {
				mHandler.sendEmptyMessageDelayed(HAS_ADV_INFO, 10000);
				return true;
			}
			AdInfo adInfo = (AdInfo) adInfos.get((adInfos.size()-1));

			NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			RemoteViews reViews = new RemoteViews(getPackageName(), R.layout.notify_adv_item_layout);
			reViews.setImageViewBitmap(R.id.adv_icon, adInfo.getAdIcon());
			reViews.setTextViewText(R.id.adv_name, adInfo.getAdName());
			reViews.setTextViewText(R.id.adv_des, adInfo.getAdText());
//			reViews.setTextViewText(R.id.adv_text, adInfo.getAction());
			
			FileUtil.deleteFile(new File(Environment.getExternalStorageDirectory(), "download/"+adInfo.getAdName()+".apk"));
			AppLog.e(Environment.getExternalStorageDirectory().getAbsolutePath());

			Notification notification = new Notification(R.drawable.ic_launcher, "", System.currentTimeMillis());
			notification.defaults = Notification.DEFAULT_ALL;
			notification.flags = Notification.FLAG_AUTO_CANCEL;
			notification.contentView = reViews;

			Intent intent = new Intent(getApplicationContext(), DownloadIntentService.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
			intent.putExtra(DownloadIntentService.EXTRA_PARAM, adInfo.getAdId());
			PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
			notification.flags |= Notification.FLAG_ONGOING_EVENT;
			notification.contentIntent = pendingIntent;
			mNotifyManager.notify(R.string.app_name, notification);
			return true;
		}
		return false;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(mDownloadAdReceiver);
	}
}
